import {
  nodeDefinitions,
  fromGlobalId,
} from 'graphql-relay';

import * as models from './models';

const getObjectFromTypeAndId = async (type, id) => {
  const typeModel = models[type];
  return await typeModel.findByPrimary(id);
};

const dataModelToGraphQLType = (modelString) => {
  try {
    return require('./types')[`${modelString}`];
  }catch(exc){
    console.log('exception in data model to graphql type');
    return null;
  }
};

const { nodeInterface, nodeField } = nodeDefinitions(
  async (globalId) => {
    const {type, id} = fromGlobalId(globalId);
    return await getObjectFromTypeAndId(type, id);
  },
  (obj) => {
    const typeString = obj.type;
    return dataModelToGraphQLType(typeString);
  }
);

export default {
  nodeInterface,
  nodeField,
}
